from django.db import transaction
from django.db.models import Q
from django.shortcuts import redirect
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from saas_main import models
from saas_main.permission.project_permission import ProjectAllowCreatePersion, ProjectDeletePersion
from saas_main.serializer.project_serializer import ProjectSerializer
from utils.tencent_cos import create_bucket, delete_bucket


class ProjectApiView(APIView):
    permission_classes = [IsAuthenticated, ProjectAllowCreatePersion]

    def post(self, request):
        data = request.data.dict()
        data.update({'creator': request.user.id})
        bucket_name = f"{request.user.mobile}-{data.get('project_title')}-1321161744"
        region = 'ap-beijing'
        create_bucket(bucket_name, region)
        data.update({'bucket': bucket_name, 'region': region})
        serializer = ProjectSerializer(data=data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    project_obj = serializer.save()
                    models.ProjectRelation.objects.create(
                        user=request.user,
                        project=project_obj,
                    )
                    objs = []
                    for title in models.IssuesType.PROJECT_INIT_LIST:
                        objs.append(models.IssuesType(title=title, project=project_obj))
                    models.IssuesType.objects.bulk_create(objs)
            except Exception as e:
                return Response({'ret': 1, "errors": {"non_field_errors": [f"创建项目失败，请稍后重试！{str(e)}"]}})
            return Response({"ret": 0, 'msg': "ok"})
        else:
            return Response({"ret": 1, 'errors': serializer.errors})

    def get(self, request):
        # 也可以根据用户分别查项目和关系表中的所有数据，并在视图中写逻辑进行QUERYSET对象的筛选和添加
        my_create_obj = models.Project.objects.filter(creator=request.user).filter(
            Q(projectrelation__star=False) & Q(projectrelation__user=request.user))
        my_join_obj = models.Project.objects.filter(
            Q(projectrelation__user=request.user) & Q(projectrelation__star=False)).exclude(creator=request.user)
        my_star_obj = models.Project.objects.filter(
            Q(projectrelation__user=request.user) & Q(projectrelation__star=True))
        create_serializer = ProjectSerializer(instance=my_create_obj, many=True)
        join_serializer = ProjectSerializer(instance=my_join_obj, many=True)
        star_serializer = ProjectSerializer(instance=my_star_obj, many=True)
        return Response({
            "ret": 0,
            'create': create_serializer.data,
            'join': join_serializer.data,
            'star': star_serializer.data
        })


class ProjectDetailApiView(APIView):
    permission_classes = [IsAuthenticated, ProjectDeletePersion]

    def delete(self, request, project):
        project_obj = models.Project.objects.filter(id=project, project_title=request.data.get('project_name')).first()
        if not project_obj:
            return Response({"ret": 1, 'errors': "未找到要删除的项目！"})
        delete_bucket(project_obj.bucket, project_obj.region)
        project_obj.delete()
        return Response({"ret": 0, 'msg': "ok"})


class ProjectStarAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        project = request.query_params.get("project")
        instance = models.ProjectRelation.objects.filter(Q(user=request.user) & Q(project=project)).first()
        if instance:
            instance.star = not instance.star
            instance.save()
            # return Response({"ret": 0, 'msg': "ok"})
            return redirect('main:project')
        return Response({"ret": 1, 'errors': "当前用户项目不存在！"})
